﻿
using Microsoft.EntityFrameworkCore;
using FreeRedis;
using Newtonsoft.Json;
using Microsoft.AspNetCore.Mvc;
using static System.Reflection.Metadata.BlobBuilder;
using Newtonsoft.Json.Linq;
using CQIE.LabAssist.Models;
using System;
using CQIE.LabAssist.PublicHelp;
using Microsoft.Extensions.Caching.Distributed;
namespace CQIE.LabAssist.DataAccesss
{

    public class BuildingService : IBuildingService
    {
        private IDistributedCache RedisCache;
        private readonly _DbContext _Db;


        public BuildingService(_DbContext db, IDistributedCache redisCache)
        {

            _Db = db;
            RedisCache = redisCache;
        }

        /// <summary>
        ///获取所有楼栋
        /// </summary>
        /// <returns></returns>
        public JsonResult getAllBuilding()
        {
            string? RedisResult = RedisCache.GetString("AllBuildings");
            if (RedisResult == null)
            {
                var allBuilding = _Db.Buildings.Include(b => b.academician).ToList();

                string jsonString = JsonConvert.SerializeObject(allBuilding);

                var options = new DistributedCacheEntryOptions
                {
                    AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(10),
                };
                RedisCache.SetString("AllBuildings", jsonString, options);

                return new JsonResult(allBuilding);
            }
            else
            {
                var cachedData = RedisCache.GetString("AllBuildings");
                var buildings = JsonConvert.DeserializeObject<List<Building>>(cachedData);
                return new JsonResult(buildings);
            }
        }
        /// <summary>
        /// 新增楼栋
        /// </summary>
        /// <param name="build"></param>
        /// <returns></returns>
        public bool addBuilding(Building build)
        {
            Building building = build;
            building.academician=_Db.Academicians.Where(ac=>ac.Id == build.academicianId).FirstOrDefault();
            _Db.Buildings.Add(building);
            return _Db.SaveChanges()>0;
        }

        /// <summary>
        /// 删除楼栋
        /// </summary>
        /// <param name="buildindId"></param>
        /// <returns></returns>
        public bool deteltBuilding(int buildindId)
        {
            Building building = _Db.Buildings.Where(w=>w.Id==buildindId).FirstOrDefault();
            _Db.Buildings.Remove(building);
            return _Db.SaveChanges() > 0;
        }

        /// <summary>
        /// 修改楼栋
        /// </summary>
        /// <param name="Building"></param>
        /// <returns></returns>
        public bool updateBuilding(Building building)
        {
            // 首先，尝试找到具有相同 Id 的楼栋记录
            Building oldbuilding = _Db.Buildings.Where(w => w.Id == building.Id).FirstOrDefault();
            if (oldbuilding == null)
            {
                // 如果找不到楼栋记录，则抛出异常或返回错误
                return false;
            }

            // 设置旧楼栋的名称和ID
            oldbuilding.Name = building.Name;
            oldbuilding.academicianId = building.academicianId;
            oldbuilding.Latitude = building.Latitude;
            oldbuilding.Longitude = building.Longitude;

            // 确保旧楼栋的记录与新楼栋的ID匹配
            oldbuilding.academician = _Db.Academicians.Where(ac => ac.Id == building.academicianId).FirstOrDefault();

            // 使用 Attach 方法避免实体跟踪冲突
            _Db.Attach(oldbuilding);
            _Db.Entry(oldbuilding).State = EntityState.Modified;

            // 更新数据库中的楼栋记录
            _Db.Buildings.Update(oldbuilding);

            // 保存更改
            return _Db.SaveChanges() > 0;
        }

    }


}
